import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Button, message, Badge, Tag, Popconfirm } from 'antd';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PropTypes from 'prop-types';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import { routerRedux } from 'dva/router';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  messageManagement: state.messageManagement,
  loading: state.loading.effects['messageManagement/getFetchPage'],
});
class MessageManagement extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    this.handleFlushPage();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'messageManagement/initData',
    });
  }

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    let params = { ...formValues, current: 1, pageSize: 10 };
    dispatch({
      type: 'messageManagement/getFetchPage',
      payload: { url: '/message/record/findByPage', ...params },
    });
  };

  // 删除/批量删除
  handleRemove = (list = []) => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'messageManagement/postList1',
      payload: { url: '/message/record/deleteRecord', list },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          this.setState({
            selectedRowKeys: selectedRowKeys.filter((item: any) => !list.includes(item)),
          });
        } else {
          message.error(response.statusMessage);
        }
        this.handleFlushPage();
      },
    });
  };

  // 取消发送
  handleCancel = (pushId: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'messageManagement/getData',
      payload: { url: '/message/record/cancelSend', pushId },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('取消发送成功');
          this.handleFlushPage();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  // 重新发送
  handleReSend = (pushId: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'messageManagement/getData',
      payload: { url: '/message/record/reSend', pushId },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('重发成功');
          this.handleFlushPage();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  render() {
    const {
      messageManagement: {
        pageData: { list, pagination },
      },
      loading,
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, selectedRowKeys } = this.state;
    const columns = [
      {
        title: '消息编号',
        dataIndex: 'pushId',
        render: (text: any) => (
          <Ellipsis length={10} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '模板编号',
        dataIndex: 'msgCd',
        render: (text: any) => (
          <Ellipsis length={10} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '模板名称',
        dataIndex: 'msgTitle',
        render: (text: any) => (
          <Ellipsis length={10} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '渠道类型',
        dataIndex: 'channelCd',
        render: (text: any) => {
          switch (text) {
            case 1:
              return '邮件';
            case 2:
              return 'JPush';
            case 3:
              return 'KAFKA';
            case 4:
              return 'MQTT';
            case 5:
              return '短信';
            case 9:
              return '第三方';
            case 99:
              return '站内信';
            default:
              return text;
          }
        },
      },
      {
        title: '渠道发送方',
        dataIndex: 'senderId',
      },
      {
        title: '接收对象',
        dataIndex: 'receiverId',
        render(val: any) {
          return <MaskText text={val} type="accept" />;
        },
      },
      //   {
      //     title: '受众对象组编号',
      //     dataIndex: 'objectGroupSid',
      //   },
      //   {
      //     title: '受众对象组名称',
      //     dataIndex: 'objectGroupName',
      //   },
      {
        title: '发送方式',
        dataIndex: 'manualFlag',
        render: (text: any) => (text === 1 ? '手动' : '自动'),
      },
      {
        title: '发送状态',
        dataIndex: 'status',
        render: (text: any, record: any) => {
          switch (record.msgStatus) {
            case 0:
              return <p style={{ color: 'red ' }}>发送失败</p>;
            case 1:
              return '待推送';
            case 2:
              return '发送中';
            case 3:
              return '待重发';
            case 4:
              return '未送达';
            case 5:
              return '发送成功';
            case 6:
              return '发送成功';
            case 7:
              return '已取消';
            default:
              return text;
          }
        },
      },
      {
        title: '发送状态更新时间',
        dataIndex: 'updateDate',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 230,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'detail',
              auth: 'messageManagement_doDetail',
              onConfirm: () => {
                sessionStorage.setItem('messagePushId', JSON.stringify(record || {}));
                dispatch(
                  routerRedux.push({
                    pathname: '/messageCenter/messageManagementDetail',
                    state: {
                      ...formValues,
                      page: pagination.current - 1,
                      size: pagination.pageSize,
                    },
                  }),
                );
              },
            },
            {
              title: '删除',
              key: 'delete',
              auth: 'messageManagement_doDel',
              message: '确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleRemove([record.pushId]),
            },
          ];
          if (record.msgStatus === 1 || record.timer) {
            btns.push({
              title: '取消发送',
              key: 'cancel',
              auth: 'messageManagement_doDelSend',
              onConfirm: () => this.handleCancel(record.pushId),
            });
          } else if ((record.msgStatus === 0 || record.msgStatus === 4) && !record.timer) {
            btns.push({
              title: '重发',
              key: 'resend',
              auth: 'messageManagement_doReSend',
              onConfirm: () => this.handleReSend(record.pushId),
            });
          }
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
      },
    };
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      rowKey: (record: any) => record.pushId,
      dataSource: list,
      loading,
      pagination: paginationProps,
      rowSelection,
      selectedRowKeys,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '消息编号',
        key: 'pushId',
      },
      {
        type: 'input',
        title: '模板编号',
        key: 'msgCd',
      },
      {
        type: 'input',
        title: '模板名称',
        key: 'msgTitle',
      },
      {
        type: 'select',
        title: '渠道类型',
        key: 'channelCd',
        selectOptions: [
          { label: '邮件', value: 1 },
          { label: 'JPush', value: 2 },
          { label: 'KAFKA', value: 3 },
          { label: 'MQTT', value: 4 },
          { label: '短信', value: 5 },
          { label: '第三方', value: 9 },
          { label: '站内信', value: 99 },
        ],
      },
      {
        type: 'input',
        title: '渠道发送方',
        key: 'senderId',
      },
      //   /* {
      //     type: 'input',
      //     title: '受众对象组编号',
      //     key: 'objectGroupSid',
      //   }, */
      //   /* {
      //     type: 'input',
      //     title: '受众对象组名称',
      //     key: 'objectGroupName',
      //   }, */
      {
        type: 'select',
        title: '发送方式',
        key: 'manualFlag',
        keyValue: ['key', 'value'],
        selectOptions: [
          { key: '0', value: '自动' },
          { key: '1', value: '手动' },
        ],
      },
      {
        title: '发送状态',
        type: 'select',
        key: 'msgStatus',
        keyValue: ['key', 'value'],
        selectOptions: [
          { key: '0', value: '发送失败' },
          { key: '1', value: '待推送' },
          { key: '2', value: '发送中' },
          { key: '3', value: '待重发' },
          { key: '4', value: '未送达' },
          { key: '5', value: '发送成功' },
          // { key:"6",value: "已读" },
          { key: '7', value: '已取消' },
        ],
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'messageManagement/getFetchPage',
              url: '/message/record/findByPage',
            }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div>
            {selectedRowKeys.length ? (
              <span>
                <Popconfirm
                  title="是否确认删除所选数据？"
                  onConfirm={() => this.handleRemove(selectedRowKeys)}
                >
                  <Button
                    style={{ marginBottom: 8, marginRight: 8 }}
                    size={'small'}
                    type={'primary'}
                    danger
                  >
                    批量删除
                  </Button>
                </Popconfirm>
                <span>{`共${selectedRowKeys.length}条`}</span>
              </span>
            ) : null}
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'messageManagement/getFetchPage',
              url: '/message/record/findByPage',
            }}
            formValues={formValues}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(MessageManagement);
